﻿using System;
using System.Collections;
using System.Data;
using System.Linq;

namespace SQLPXBase.Factory.Keys
{
    public abstract class PrimaryKey
    {
        public bool ConvertNullToEmptyString { get; set; }

        public abstract bool IsEmpty { get; }
        public abstract PrimaryKey DefaultValue { get; }

        public abstract object GetSingleValue { get; }
        public abstract object[] GetValues { get; }
        public abstract int KeyLength { get; }

        protected PrimaryKey()
        {
            ConvertNullToEmptyString = false;
        }

        protected PrimaryKey(DataRow rw, params string[] fieldNames) : this()
        {
            if (fieldNames.Length != KeyLength)
                throw new KeyLengthMismatchExceptions();

            try
            {
                ArrayList tmp = new ArrayList();
                foreach (string fieldName in fieldNames)
                    tmp.Add(rw[fieldName]);
                SetValues(tmp.ToArray().SafeFromDb());
            }
            catch(Exception ex)
            {
                throw new PrimaryKeyException(ex.Message, ex);
            }
        }

        public abstract void SetValues(object[] values);

        public string GeneratePrimaryKeyCondition(params string[] fieldNames)
        {
            string res = "";

            object[] tmp = GetValues;
            if (fieldNames.Length != tmp.Length)
                throw new KeyLengthMismatchExceptions();

            int i = 0;
            foreach (string fieldName in fieldNames)
            {
                res += string.Format("{0}{1}{2}{3}",
                    res.Length > 0 ? " AND " : "",
                    fieldName,
                    tmp[i] != null || ConvertNullToEmptyString ? " = " : " IS NULL ",
                    Utils.SqlValueToString(tmp[i]));
                i++;
            }
            return res;
        }

        protected void CheckValues(object[] values)
        {
            if (values.Length != KeyLength)
                throw new KeyLengthMismatchExceptions();
        }

        public override string ToString()
        {
            return ToString();
        }
        public string ToString(char separator = '-')
        {
            object[] tmp = GetValues;
            if (tmp == null) return null;
            return tmp.Aggregate((current, next) => string.Format("{0}{1}{2}", current, separator, next)) as string ??
                   "";
        }
    }
}
